<script setup lang="ts">
import { getCurrentInstance, ref, reactive, onMounted, nextTick } from 'vue'
import { onBeforeRouteLeave } from 'vue-router'
const { proxy } = getCurrentInstance()

/* ---- */
const userInfo = proxy.$Store.get('userInfo') || {}
let logUser = proxy.$Store.get('logUser') || {}
const WXConfig = proxy.$Store.get('WXConfig') || {}
const forSys = proxy.$Sys || []
const forInit = proxy.$Init || {}

/* --设置微信分享功能-- */
proxy.$WxTool.loadJsdk(WXConfig, (obj) => {
  if (!obj) return
  // ----
  obj.hideMenuItem()
})

/* ---- */
const user = {
  empty_title: proxy.$Myfun.setText(forInit.empty_title),
  empty_desc: proxy.$Myfun.setText(forInit.empty_desc),
  // ----
  title: proxy.$route.query.name,
  // ----
  forAdm: String(proxy.$Phone) === String(logUser.telphone)
}
// ----
const myCityData = proxy.$City
const tags = ref([])
const busis = ref([])
// ----
const advs = reactive({
  add: true,
  maxnum: 0,
  forFree: 1,
  setTrueStyle: {},
  imgs: [],
  option: {
    viewMode: 0,
    dragMode: 'move',
    autoCropArea: 1,
    center: false,
    cropBoxMovable: false,
    cropBoxResizable: false,
    toggleDragModeOnDblclick: false
  },
  cropImg: proxy.$Global.cropImg
})
// ----
const form = reactive({
  name: '',
  desc: '',
  leader: '',
  sex: 1,
  addrCity: '',
  address: '',
  tag: ',',
  // ----
  busiText: '',
  busi: 0
})

/* ---- */
const pickerBusi = ref()
const pickerCity = ref()
const uploadoss = ref()
const layer = ref()
const layerBox = ref()
const layerLoading = ref()

/* ---- */
const setAppTitle = (title) => {
  document.title = title
  // --利用iframe的onload事件刷新页面--
  const iframe = document.createElement('iframe')
  iframe.style.visibility = 'hidden'
  iframe.style.width = 0
  iframe.style.height = 0
  document.body.appendChild(iframe)
  nextTick(() => { document.body.removeChild(iframe) })
}
// ----
const getFormInfo = async () => {
  advs.setTrueStyle = { height: `${document.querySelector('.squareBox dl dd label').clientWidth / advs.forFree}px` }
  // ----
  if (proxy.$route.query.dealer_id) {
    await proxy.$http.get('dealer/index', {
      params: { 'DealerSearch[id]': proxy.$route.query.dealer_id }
    }).then((res) => {
      if (Number(res.items.length) > 0) logUser = res.items[0]
    }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  }
  // ----
  form.name = proxy.$Myfun.setText(logUser.name)
  form.desc = proxy.$Myfun.setText(logUser.remark)
  form.leader = proxy.$Myfun.setText(logUser.leader)
  if (Number(logUser.gender) > 0) form.sex = logUser.gender
  form.address = proxy.$Myfun.setText(logUser.address)
  if (logUser.maincate_id && Number(logUser.maincate_id.length) > 0) form.tag = logUser.maincate_id
  if (Number(logUser.connections_type.split(',').length) > 0) form.busi = logUser.connections_type.split(',')[1]
  // ----
  let forCity = ''
  if (logUser.district) {
    forCity = logUser.province + ' - ' + logUser.city + ' - ' + logUser.district
  } else if (logUser.city) {
    forCity = logUser.province + ' - ' + logUser.city
  } else if (logUser.province) {
    forCity = logUser.province
  }
  form.addrCity = forCity
  // ----
  document.querySelectorAll('.form-sex input[type="radio"]').forEach((item) => {
    if (Number(item.value) === Number(form.sex)) document.querySelector('.form-sex label[for="' + item.getAttribute('id') + '"]').querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
  })
  // --获取商友属性--
  const busiItems = forSys.filter((item) => { return String(item.name) === 'market_busiattrib' })
  if (Number(busiItems.length) === 1) {
    await proxy.$Myfun.getJsonData(busiItems[0].value, (resJson) => {
      const newItems = []
      resJson[0].list.forEach((item, index) => {
        newItems.push({
          value: String(item.id),
          text: proxy.$Myfun.setText(item.name)
        })
      })
      busis.value = newItems
    })
  }
  // ----
  busis.value.some((current) => {
    if (String(current.value) === String(form.busi)) form.busiText = current.text
  })
  // --获取行业分类--
  const forTagData = {
    params: {
      sort: 'SORT_ASC',
      // ----
      page: 1,
      PageSize: 1000000
    }
  }
  await proxy.$Axios.all([
    proxy.$Axios.get('maincate/index', forTagData)
  ]).then(proxy.$Axios.spread((tagData) => {
    const tagItems = []
    tagData.items.forEach((item, index) => {
      tagItems.push({
        value: String(item.id),
        text: proxy.$Myfun.setText(item.name)
      })
    })
    tags.value = tagItems
  })).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // --获取图文详情--
  proxy.$Myfun.getJsonData(logUser.intention, (resJson) => {
    resJson.forEach((item) => {
      advs.imgs.push({
        imgName: item.name,
        imgUrl: item.image,
        imgW: item.width,
        imgH: item.height
      })
    })
    if (Number(advs.imgs.length) >= Number(advs.maxnum) && Number(advs.maxnum) > 0) advs.add = !advs.add
  })
  // --设置网页title--
  const forTitle = user.title || document.title
  setAppTitle(forTitle)
}
// --上传图片操作--
const uploadAct = (type, selectObj, event, index) => {
  const uploadOss = uploadoss.value
  switch (Number(type)) {
    case 1: {
      uploadOss.uploadImg(event, selectObj,'imgs', index)
      break
    }
    case 2: {
      uploadOss.delInfo(selectObj, event)
      break
    }
    case 3: {
      uploadOss.uploadImgMoreWX(selectObj)
      break
    }
  }
}
// ----
const emptyInfo = (event) => {
  const curEL = event.currentTarget
  const input = curEL.parentElement.querySelector('input')
  input.value = ''
  input.dispatchEvent(new Event('input'))
}
// ----
const getAuditFun = (type, item) => {
  switch (Number(type)) {
    case 1: {
      const options = {
        type: 1,
        isFirst: true,
        button: ['取消', '确定'],
        initData: busis.value,
        yes: (result) => {
          form.busiText = result[0].text
          form.busi = result[0].value
        }
      }
      proxy.$Myfun.isIndepth(pickerBusi.value, 'open', options)
      break
    }
    case 2: {
      const curEL = item.currentTarget
      const parentEL = curEL.parentElement
      // ----
      parentEL.querySelectorAll('label').forEach((curItem) => { curItem.querySelector('b').setAttribute('class', 'fal fa-circle xw-color-16') })
      curEL.querySelector('b').setAttribute('class', 'fa fa-dot-circle xw-color-12')
      break
    }
    case 3: {
      const options = {
        type: 3,
        button: ['取消', '确定'],
        initData: myCityData,
        yes: (result) => {
          let resText = ''
          result.forEach((curItem, index) => {
            resText += (index > 0 ? ' - ' : '') + curItem.text
          })
          form.addrCity = resText
        }
      }
      proxy.$Myfun.isIndepth(pickerCity.value, 'open', options)
      break
    }
    case 4: {
      if (form.tag.indexOf(',' + item.value + ',') >= 0) {
        const reg = new RegExp(',' + item.value + ',', 'g')
        form.tag = form.tag.replace(reg, ',')
        return false
      }
      // ----
      form.tag = ',' + item.value + ','
      break
    }
  }
}
// ----
const subform = async () => {
  if (Number(form.name.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写名称标题！')
    return false
  }
  if (Number(busis.value.length) > 0 && Number(form.busiText.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择商友属性！')
    return false
  }
  if (Number(form.leader.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写业务负责人姓名！')
    return false
  }
  if (Number(form.leader.length) > 10) {
    proxy.$Myfun.forToast(layer.value, 'open', '业务负责人最多10个字！')
    return false
  }
  if (Number(form.addrCity.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择所属地区！')
    return false
  }
  if (Number(form.address.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请填写详细地址！')
    return false
  }
  if (Number(form.tag.split(',').length) <= 2) {
    proxy.$Myfun.forToast(layer.value, 'open', '请选择行业分类！')
    return false
  }
  if (Number(advs.imgs.length) === 0) {
    proxy.$Myfun.forToast(layer.value, 'open', '请上传图文介绍！')
    return false
  }
  // ----
  const forCity = form.addrCity.split(' - ')
  // ----
  let forAdvs = ''
  if (Number(advs.imgs.length) > 0) {
    const advItems = []
    advs.imgs.forEach((item, index) => {
      advItems.push({
        name: item.imgName,
        image: item.imgUrl,
        width: item.imgW,
        height: item.imgH
      })
    })
    forAdvs = JSON.stringify(advItems)
  }
  // ----
  const forBusis = ',' + form.busi + ','
  // ----
  const forType = 'patch'
  const forUrl = 'dealer/update?id=' + logUser.id
  const forData = {
    is_news: user.forAdm ? undefined : 2,
    // --打开推广展示--
    is_popularize: user.forAdm ? undefined : 1,
    // --信息审核默认通过--
    is_stoped: user.forAdm ? undefined : 1,
    // ----
    name: form.name,
    remark: form.desc,
    leader: form.leader,
    gender: form.sex,
    province: forCity[0],
    city: forCity[1],
    district: forCity[2],
    address: form.address,
    maincate_id: form.tag,
    connections_type: forBusis,
    intention: forAdvs,
    // ----
    config_id: userInfo.config_id,
    openid: userInfo.openid
  }
  // ----
  proxy.$Myfun.onLoading(layerLoading.value, 'open', proxy.$Global.loadingMsg)
  let resData = ''
  await proxy.$http[forType](forUrl, forData).then((res) => { resData = res }).catch((err) => { proxy.$Myfun.forToast(layer.value, 'open', err) })
  // ----
  proxy.$Myfun.disLoading(layerLoading.value, 'close')
  if (resData) {
    const forOptions = {
      shadeClose: false,
      content: '信息提交成功',
      desc: '展示在商务中心 — 万域商友栏目中',
      button: [{
        text: proxy.$Global.layer.btnCancel,
        callback: () => {
          layerBox.value.close()
          // ----
          proxy.$router.back()
        }
      }, {
        text: '商务中心',
        class: 'xw-color-24',
        callback: () => {
          layerBox.value.close()
          // ----
          proxy.$Myfun.openPage(proxy, 'push', 'UcenTer')
        }
      }]
    }
    proxy.$Myfun.isIndepth(layerBox.value, 'open', forOptions)
  }
}
const goback = () => { proxy.$router.back() }

/* ---- */
onMounted(() => {
  getFormInfo()
})
onBeforeRouteLeave(() => { proxy.$Myfun.setScrollTop(proxy.$refs.formSection) })
</script>

<template>
  <div class="mescroll-touch" ref="formSection">
    <div class="formSet">
      <ul>
        <li>
          <div class="form-are xw-radius-3">
            <h1>名称标题</h1>
            <p><textarea class="tarea-H3" :placeholder="user.empty_title" v-model.trim="form.name"></textarea></p>
          </div>
        </li>
        <li v-if="Number(busis.length) > 0">
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>商务属性</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model.trim="form.busiText" @click="getAuditFun(1)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.busiText"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>业务负责</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="请填写业务负责人姓名" v-model.trim="form.leader"/></p>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.leader"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>性别属性</i>
            <p class="xw-flex-W1"></p>
            <div class="form-sex xw-flex xw-flex-align">
              <input type="radio" id="male" value="1" v-model="form.sex"/>
              <input type="radio" id="female" value="2" v-model="form.sex"/>
              <label for="male" class="xw-flex xw-flex-align" @click="getAuditFun(2, $event)"><b class="fal fa-circle xw-color-16"></b>男</label>
              <label for="female" class="xw-flex xw-flex-align" @click="getAuditFun(2, $event)"><b class="fal fa-circle xw-color-16"></b>女</label>
            </div>
          </div>
        </li>
        <li>
          <div class="form-txt xw-radius-3 xw-flex xw-flex-align">
            <i>所属地区</i>
            <p class="xw-flex-W1"><input class="text" type="text" placeholder="" v-model="form.addrCity" @click="getAuditFun(3)" readonly unselectable="on" onfocus="this.blur()"/></p>
            <span class="fa fa-caret-down xw-color-16"></span>
            <transition name="fade"><em class="fa fa-times-circle" @click="emptyInfo" v-if="form.addrCity"></em></transition>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>详细地址</h1>
            <p><textarea class="tarea-H2" placeholder="" v-model.trim="form.address"></textarea></p>
          </div>
        </li>
        <li>
          <div class="form-more xw-radius-3">
            <h1>所属行业</h1>
            <dl>
              <dd class="form-more-W3" v-for="(item, index) in tags" :class="{'active': Number(form.tag.indexOf(',' + item.value + ',')) !== Number(-1)}" @click="getAuditFun(4, item)"><div class="xw-radius-3"><span class="xw-block xw-ellipsis">{{item.text}}</span></div></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-imgs xw-radius-3 squareBox">
            <div class="FIS-top xw-flex xw-flex-align xw-flex-justify">
              <span class="FIS-title">广告图片</span>
              <span v-if="Number(advs.maxnum) > 0">数量：最多{{advs.maxnum}}张</span>
            </div>
            <dl class="FIS-img xw-float">
              <dd class="xw-float-W3" v-for="(item, index) in advs.imgs"><label class="xw-block xw-act" :style="advs.setTrueStyle"><div class="xw-bgImg" :style="{ backgroundImage: 'url(' + item.imgUrl + ')' }"></div><input type="file" style="display: none;" accept="image/*" @change="uploadAct(1, advs, $event, index)"/></label><span class="FIS-del fal fa-times xw-act" @click="uploadAct(2, advs, index)"></span></dd>
              <dd class="xw-float-W3" v-if="advs.add"><label class="xw-act xw-flex xw-flex-center" :style="advs.setTrueStyle" @click="uploadAct(3, advs)"><em class="fal fa-plus"></em></label></dd>
            </dl>
          </div>
        </li>
        <li>
          <div class="form-are xw-radius-3">
            <h1>业务描述</h1>
            <p><textarea class="tarea-H5" :placeholder="user.empty_desc" v-model.trim="form.desc"></textarea></p>
          </div>
        </li>
      </ul>
      <div class="form-sub xw-radius-3 xw-bgCL-11 xw-act" @click="subform">确定提交</div>
      <div class="form-sub xw-radius-3 xw-WhiteRed xw-act" @click="goback">取消返回</div>
    </div>
    <picker-view ref="pickerBusi"/>
    <picker-view ref="pickerCity"/>
    <uploadoss-view ref="uploadoss"/>
    <layer-view ref="layer"/>
    <layer-view ref="layerBox"/>
    <layer-view ref="layerLoading"/>
  </div>
</template>